﻿using System.Collections.Generic;
using System.Linq;
using Apps.Web.Core;
using Apps.Locale;
using System.Web.Mvc;
using Apps.Common;
using Apps.IBLL;
using Apps.Models.PUB;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Data;
using Apps.IBLL.PL;
using Apps.Models;
using Wantn.FIS.Enum;
using Apps.IBLL.PUB;
using System.Web;
using System.IO;

namespace Apps.Web.Areas.PUB.Controllers
{
    public class CARController : BaseController
    {
        [Dependency]
        public IPUB_CARBLL m_BLL { get; set; }

        [Dependency]
        public IPUB_CAR_BLACKLISTBLL m_BackListBLL { get; set; }
        [Dependency]
        public IPL_RC_TRANSPORTBLL m_RC_TRANSPORTBLL { get; set; }
        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetList(GridPager pager, string queryStr)
        {
            try
            {

                List<PUB_CAR> list = m_BLL.GetList(ref pager, queryStr);
                GridRows<PUB_CAR> grs = new GridRows<PUB_CAR>();
                grs.rows = list;
                grs.total = pager.totalRows;
                return Json(grs);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        private bool isRepeated(PUB_CAR model)
        {
            bool result = false;
            List<PUB_CAR> oldList = m_BLL.GetList(p => p.LPR == model.LPR && p.CAR_ID != model.CAR_ID);
            if (oldList.Count > 0)
            {
                result = true;
            }
            return result;

        }

        [HttpPost]
        [SupportFilter(ActionName = "Edit")]
        public JsonResult ChangeState(string CarID)
        {

            if (!string.IsNullOrWhiteSpace(CarID))
            {
                PUB_CAR mode = m_BLL.GetById(CarID);
                if (mode != null)
                {
                    mode.STATUS = mode.STATUS == 0 ? 2 : 0;
                    if (m_BLL.Edit(ref errors, mode))
                    {
                        LogHandler.WriteServiceLog(GetUserId(), "ENABLED" + mode.CAR_ID, "成功", "修改状态", "PUB_CAR");
                        return Json(JsonHandler.CreateMessage(1, "状态修改成功！"));
                    }
                    else
                    {
                        string ErrorCol = errors.Error;
                        LogHandler.WriteServiceLog(GetUserId(), "ENABLED" + mode.CAR_ID + "," + ErrorCol, "失败", "修改状态", "PUB_CAR");
                        return Json(JsonHandler.CreateMessage(0, "状态修改失败！" + ErrorCol));
                    }

                }
                else
                {
                    return Json(JsonHandler.CreateMessage(0, "更改状态失败，传入主键为空"));
                }

            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, "更改状态失败，传入主键为空"));
            }
        }

        #region 创建
        [SupportFilter]
        public ActionResult Create()
        {
            ViewBag.CarStatus = new SelectList(EnumMvcHelper.GetEnumAllDesc<CarStatus>(), "Key", "Desc");
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Create(PUB_CAR model)
        {
            model.CAR_ID = ResultHelper.NewId;
            model.REGISTER_USER_ID = GetUserId();
            model.REGISTER_TIME = DateTime.Now;
            model.UPDATE_TIME = DateTime.Now;
            model.UPDATE_USER_ID = GetUserId();
            model.RFID = string.IsNullOrEmpty(model.RFID) ? "0" : model.RFID;
            if (model != null && ModelState.IsValid)
            {
                if (isRepeated(model))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在该车牌的车辆信息!"));
                }

                if (m_BLL.Create(ref errors, model))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "TOTLE_LENGTH" + model.TOTLE_LENGTH + ",TOTLE_WIDTH" + model.TOTLE_WIDTH, "成功", "创建", "PUB_CAR");
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "TOTLE_LENGTH" + model.TOTLE_LENGTH + ",TOTLE_WIDTH" + model.TOTLE_WIDTH + "," + ErrorCol, "失败", "创建", "PUB_CAR");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }
        #endregion

        #region 修改
        [SupportFilter]
        public ActionResult Edit(string id)
        {
            PUB_CAR entity = m_BLL.GetById(id);
            ViewBag.CarStatus = new SelectList(EnumMvcHelper.GetEnumAllDesc<CarStatus>(), "Key", "Desc");
            return View(entity);
        }


        #region 黑名单添加
        [SupportFilter(ActionName = "Edit")]
        public ActionResult BackListAdd(string CadID)
        {
            ViewBag.CarID = CadID;
            PUB_CAR_BLACKLISTModel car = m_BackListBLL.GetLastBlackListById(CadID);
            if (car != null)
            {
                return View(car);
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        [SupportFilter(ActionName = "Edit")]
        public JsonResult BackListAdd(PUB_CAR_BLACKLISTModel model)
        {
            model.UPDATE_USER_ID = GetUserId();
            if (model != null)
            {
                bool status = model.STATUS;
                PUB_CAR_BLACKLISTModel carm = m_BackListBLL.GetLastBlackListById(model.CAR_ID);
                if (carm != null)
                {
                    model.UPDATE_TIME = carm.UPDATE_TIME;
                    model.STATUS = false;
                    m_BackListBLL.Edit(ref errors, model);
                }

                model.UPDATE_TIME = DateTime.Now;
                model.STATUS = !status;
                if (m_BackListBLL.Create(ref errors, model))
                {
                    PUB_CAR car = m_BLL.GetById(model.CAR_ID);
                    if (car != null)
                    {
                        if (status)
                        {
                            car.STATUS = 0;
                        }
                        else
                        {
                            car.STATUS = 1;
                        }
                        m_BLL.Edit(ref errors, car);
                    }
                    LogHandler.WriteServiceLog(GetUserId(), "CAR_ID" + model.CAR_ID + ",REASON" + model.REASON, "成功", "创建", "PUB_CAR");
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "CAR_ID" + model.CAR_ID + ",REASON" + model.REASON + "," + ErrorCol, "失败", "创建", "PUB_CAR");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, "保存信息失败!"));
            }
        }

        #endregion

        [HttpPost]
        [SupportFilter(ActionName = "Save")]
        public JsonResult Edit(PUB_CAR model)
        {
            if (model != null)
            {
                if (isRepeated(model))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在该车牌的车辆信息!"));
                }

                model.UPDATE_USER_ID = GetUserId();
                model.UPDATE_TIME = DateTime.Now;
                if (m_BLL.Edit(ref errors, model))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "TOTLE_LENGTH" + model.TOTLE_LENGTH + ",TOTLE_WIDTH" + model.TOTLE_WIDTH, "成功", "修改", "PUB_CAR");
                    return Json(JsonHandler.CreateMessage(1, Resource.EditSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "TOTLE_LENGTH" + model.TOTLE_LENGTH + ",TOTLE_WIDTH" + model.TOTLE_WIDTH + "," + ErrorCol, "失败", "修改", "PUB_CAR");
                    return Json(JsonHandler.CreateMessage(0, Resource.EditFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
        }
        #endregion

        #region 详细
        [SupportFilter]
        public ActionResult Details(string id)
        {
            PUB_CAR entity = m_BLL.GetById(id);
            ViewBag.CarStatus = new SelectList(EnumMvcHelper.GetEnumAllDesc<CarStatus>(), "Key", "Desc");
            return View(entity);
        }

        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                if (m_RC_TRANSPORTBLL.GetList(p => p.CAR_ID == id).Count() > 0)
                {
                    return Json(JsonHandler.CreateMessage(0, "该车辆已被使用,删除失败！"));
                }
                if (m_BLL.Delete(ref errors, id))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "TOTLE_LENGTH:" + id, "成功", "删除", "PUB_CAR");
                    return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "TOTLE_LENGTH" + id + "," + ErrorCol, "失败", "删除", "PUB_CAR");
                    return Json(JsonHandler.CreateMessage(0, "该车辆已被使用,删除失败！"));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion
        #region 导出导入
        [SupportFilter(ActionName = "Import")]
        public ActionResult Import(string filePath)
        {
            var list = new List<PUB_CAR>();
            bool checkResult = m_BLL.CheckImportData(filePath, list, ref errors);
            //校验通过直接保存
            if (checkResult)
            {
                m_BLL.SaveImportData(list);
                LogHandler.WriteServiceLog(GetUserId(), "导入成功", "成功", "导入", "PUB_CAR");
                return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
            }
            else
            {

                string ErrorCol = errors.Error;
                LogHandler.WriteServiceLog(GetUserId(), ErrorCol, "失败", "导入", "PUB_CAR");
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
            }
        }
        //[HttpPost]
        //[SupportFilter]
        //public ActionResult ABC(string filePath)
        //{
        //    var list = new List<PUB_CARModel>();
        //    bool checkResult = m_BLL.CheckImportData(Utils.GetMapPath(filePath), list, ref errors);
        //    //校验通过直接保存
        //    if (checkResult)
        //    {
        //        m_BLL.SaveImportData(list);
        //        LogHandler.WriteServiceLog(GetUserId(), "导入成功", "成功", "导入", "PUB_CAR");
        //        return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
        //    }
        //    else
        //    {
        //        string ErrorCol = errors.Error;
        //        LogHandler.WriteServiceLog(GetUserId(), ErrorCol, "失败", "导入", "PUB_CAR");
        //        return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
        //    }
        //}
        [HttpPost]
        [SupportFilter(ActionName = "Query")]
        public JsonResult CheckExportData(string queryStr)
        {
          
            List<PUB_CAR> list = m_BLL.GetList(ref GridPager.NotPage, queryStr);
            if (list.Count().Equals(0))
            {
                return Json(JsonHandler.CreateMessage(0, "没有可以导出的数据"));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(1, "可以导出"));
            }
        }
        [SupportFilter]
        public ActionResult Query(string queryStr)
        {
           // List<PUB_CARModel> list = m_BLL.GetList(ref setNoPagerAscById, "");
            List<PUB_CAR> list = m_BLL.GetList( ref GridPager.NotPage, queryStr);
            JArray jObjects = new JArray();
                foreach (var item in list)
                {
                    var jo = new JObject();
                    jo.Add("总长", item.TOTLE_LENGTH);
                    jo.Add("车宽", item.TOTLE_WIDTH);
                    jo.Add("车厢长", item.LENGTH);
                    jo.Add("车厢宽", item.WIDTH);
                    jo.Add("车底高", item.HEIGHT);
                    jo.Add("拉筋位置", item.POSTIONS);
                    jo.Add("第一次注册用户", item.REGISTER_USER_ID);
                    jo.Add("登记时间", item.REGISTER_TIME);
                    jo.Add("最后一次更新用户", item.UPDATE_USER_ID);
                    jo.Add("最后一次更新时间", item.UPDATE_TIME);
                    jo.Add("车辆状态", item.STATUS);
                    jo.Add("注销时间", item.UNREGISTER_TIME);
                    jo.Add("注销原因", item.UNREGISTER_REASON);
                    jo.Add("汽运货车编号", item.CAR_ID);
                    jo.Add("RFID卡号", item.RFID);
                    jo.Add("牌照号码", item.LPR);
                    jo.Add("驾驶员身份证", item.DRIVER_IDCARD);
                    jo.Add("手机", item.DRIVER_PHONE);
                    jo.Add("额定载重", item.SPECIFIED_WEIGHT);
                    jo.Add("皮重", item.TARE);
                    jo.Add("车厢尺寸", item.CAR_SIZE);
                jObjects.Add(jo);
                }
                var dt = JsonConvert.DeserializeObject<DataTable>(jObjects.ToString());
                var exportFileName = string.Concat(
                    "车辆信息",
                    DateTime.Now.ToString("yyyyMMddHHmmss"),
                    ".xlsx");
                return new ExportExcelResult
                {
                    SheetName = "Sheet1",
                    FileName = exportFileName,
                    ExportData = dt
                };
            }
        #endregion
    }
}

